package com.atguigu.order.controller;

import com.atguigu.commonUtils.JwtUtils;
import com.atguigu.commonUtils.R;
import com.atguigu.order.entity.Order;
import com.atguigu.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Rayyy666
 * @since 2022-04-20
 */
@RestController
@RequestMapping("/order/order")
//@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 生成订单，返回订单号
     *
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request) {

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (memberId == null) {
            return R.error().message("要购买课程请先登录！");
        }

        //创建订单，返回订单号
        String orderNo = orderService.createOrderByCourseId(courseId, memberId);
        return R.ok().data("orderId", orderNo);
    }

    /**
     * 根据订单号 获取订单信息
     *
     * @param orderId
     * @return
     */
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {

        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderId));
        return R.ok().data("item", order);
    }

    /**
     * 根据课程ID 和 用户ID 查询订单表中订单状态
     *
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public Boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        //查询用户是否购买课程
        int count = orderService.count(wrapper.eq("course_id", courseId).eq("member_id", memberId).eq("status", 1));

        if (count > 0) {//已经支付
            return true;
        } else {//没有支付，查不到订单记录
            return false;
        }
    }
}

